
import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage, useAccess } from '@umijs/max';
import type { FormInstance} from 'antd';
import { Button, Dropdown, message, Modal,Switch,Space ,Tag} from 'antd';
import { ActionType, FooterToolbar, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { PlusOutlined, DeleteOutlined, ExclamationCircleOutlined ,DownOutlined} from '@ant-design/icons';
import { getTenant,getTenantList, removeTenant, addTenant, updateTenant, exportTenant,updateTenantApproval } from '@/services/system/tenant';
import UpdateForm from './edit';
import { getDictValueEnum } from '@/services/system/dict';
import DictTag from '@/components/DictTag';
import { getMenuTree } from '@/services/system/menu';
import { formatTreeData } from '@/utils/tree';
import MerchInCome from './merchInCome';
import BindCardComfirm from "./bindCardConfirm"
import { getTenantpackageSimpleList } from '@/services/system/tenantpackage';


/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields: API.System.Tenant) => {
  const hide = message.loading('正在添加');
  try {
    const resp = await addTenant({ ...fields });
    hide();
    if (resp.code === 200) {
      message.success('添加成功');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.System.Tenant) => {
  const hide = message.loading('正在更新');
  try {
    const resp = await updateTenant(fields);
    hide();
    if (resp.code === 200) {
      message.success('更新成功');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};



/**
 * 更新节点 审核
 *
 * @param fields
 */
const handleUpdateApproval = async (fields: API.System.Tenant) => {
  const hide = message.loading('正在更新');
  try {
    const resp = await updateTenantApproval(fields);
    hide();
    if (resp.code === 200) {
      message.success('更新成功');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};


/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.System.Tenant[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    const resp = await removeTenant(selectedRows.map((row) => row.id).join(','));
    hide();
    if (resp.code === 200) {
      message.success('删除成功，即将刷新');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const handleRemoveOne = async (selectedRow: API.System.Tenant) => {
  const hide = message.loading('正在删除');
  if (!selectedRow) return true;
  try {
    const params = [selectedRow.id];
    const resp = await removeTenant(params.join(','));
    hide();
    if (resp.code === 200) {
      message.success('删除成功，即将刷新');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 导出数据
 *
 * 
 */
const handleExport = async () => {
  const hide = message.loading('正在导出');
  try {
    await exportTenant();
    hide();
    message.success('导出成功');
    return true;
  } catch (error) {
    hide();
    message.error('导出失败，请重试');
    return false;
  }
};




const TenantTableList: React.FC = () => {
  const formTableRef = useRef<FormInstance>();  

  const [modalVisible, setModalVisible] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.System.Tenant>();
  const [selectedRows, setSelectedRows] = useState<API.System.Tenant[]>([]);

  const [statusOptions, setStatusOptions] = useState<any>([]);
  const [tenantpackages, setTenantpackages] = useState<Map<any, any>>();

  const approvalStatusOptions = { '0': '待审批', '1': '审批通过', '2': '审批拒绝' };
  const signAppStatusOptions = { '0': '待审批', '1': '审批通过', '2': '审批拒绝','-1':'未发起签约','3':'提交申请失败','4':'未发起签约' };
  const signAppStatusColorOptions = { '0': 'processing', '1': 'success', '2': 'error','-1':'default','3':'warning','4':'default' };
  const colorOptions={'0':'processing','1':'success','2':'error'}
  const access = useAccess();

  /**控制商户进件弹框的显示 */
  const [showMerchInComeBox,setShowMerchInComeBox]=useState<boolean>(false)
  const [merchId,setMerchId]=useState<number|null>(null)

  /** 绑卡确认*/
  const [showBindCardConfirmBox,setShowBindCardConfirmBox]=useState<boolean>(false)
  const [ bcTenantName,setbcTenantName]=useState<string>("")

  /** 国际化配置 */
  const intl = useIntl();

 

  const reqSimpleList = async () => {
    if (tenantpackages) {
      return true;
    }
    let issuccess = false;
    await getTenantpackageSimpleList().then((res: any) => {
      if (res.code === 200) {
        let map = {};
        for (let i = 0; i < res.data.length; i++) {
          let item = res.data[i];
          map[item.id] = item.name;
        }
        setTenantpackages(map);

        // alert(JSON.stringify(res.data));
        issuccess = true;
      } else {
        message.warning(res.msg);
      }
    });

    return issuccess;
  };

  useEffect(() => {
    getDictValueEnum('sys_normal_disable').then((data) => {
      setStatusOptions(data);
    });
    reqSimpleList();
  }, []);
 
  const columns: ProColumns<API.System.Tenant>[] = [
    {
      title: <FormattedMessage id="system.Tenant.id" defaultMessage="商户编码" />,
      dataIndex: 'id',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="system.Tenant.tenantName" defaultMessage="商户名称" />,
      dataIndex: 'tenantName',
      valueType: 'text',
    },
    {
      title: <FormattedMessage id="system.Tenant.userName" defaultMessage="管理员账号" />,
      dataIndex: 'userName',
      valueType: 'text',
    },
    {
      title: <FormattedMessage id="system.Tenant.userPhone" defaultMessage="手机号" />,
      dataIndex: 'userPhone',
      valueType: 'text',
    },
    {
      title: <FormattedMessage id="system.Tenant.tenantPackage" defaultMessage="商户套餐" />,
      dataIndex: 'tenantPackage',
      valueType: 'text',
      valueEnum: tenantpackages,
      hideInSearch: true,

    },
    {
      title: <FormattedMessage id="system.Tenant.tenantTime" defaultMessage="商户结束时间" />,
      dataIndex: 'tenantTime',
      valueType: 'dateRange',
      render: (_, record) => {
        return (<span>{record.tenantTime} </span>);
      },
      search: {
        transform: (value) => {
          return {
            'params[beginTenantTime]': value[0],
            'params[endTenantTime]': value[1],

            // 'params%5BbeginTenantTime%5D':  value[0],
            // 'params%5BendTenantTime%5D': value[1],
          };
        },
      },
    },
    {
      title: <FormattedMessage id="system.Tenant.status" defaultMessage="商户套餐状态" />,
      dataIndex: 'status',
      valueType: 'select',
      hideInSearch: true,
      valueEnum: statusOptions,
      render: (_, record) => {
        return <DictTag enums={statusOptions} value={record.status} />;
      },
    },
    {
      title: '入驻审核状态',
      dataIndex: 'approvalStatus',
      valueType: 'select',
      // hideInSearch: true,
      valueEnum: approvalStatusOptions,
      // render: (_, record) => {
      //   return <DictTag enums={approvalStatusOptions} value={record.approvalStatus} />;
      // },
    },
    {
      title: '影印件采集状态',
      dataIndex: 'imgCollectionStatus',
      valueType: 'select',
      hideInSearch: true,
      align:"center",
      valueEnum: approvalStatusOptions,
      render: (_, record) => {
        return <Tag color={colorOptions[record.imgCollectionStatus]}>{approvalStatusOptions[record.imgCollectionStatus]}</Tag>;
      },
    },
    {
      title: '开户绑卡状态',
      dataIndex: 'userCardStatus',
      valueType: 'select',
      hideInSearch: true,
      align:"center",
      valueEnum: approvalStatusOptions,
      render: (_, record) => {
        return <Tag color={colorOptions[record.userCardStatus]}>{approvalStatusOptions[record.userCardStatus]}</Tag>;
      },
    },
    {
      title: '网签申请状态',
      dataIndex: 'signAppStatus',
      valueType: 'select',
      hideInSearch: true,
      align:"center",
      valueEnum: signAppStatusOptions,
      render: (_, record) => {
        console.log("record:",record.signAppStatus)
        return <Tag color={signAppStatusColorOptions[record.signAppStatus]}>{signAppStatusOptions[record.signAppStatus]}</Tag>;
      },
    },

   
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="操作" />,
      dataIndex: 'option',
      width: '220px',
      valueType: 'option',
      render: (_, record) => [
        <Button
          type="link"
          size="small"
          key="edit"
          hidden={!access.hasPerms('system:tenant:edit')}
          onClick={() => {

           
            // setMenuTree(menuTree)
            setTenantpackages(tenantpackages);

            getTenant(record.id).then((res) => {
              if (res.code === 200) {
                // const treeData = formatTreeData(res.menus);
                // setMenuTree(treeData);
                // setMenuIds(res.data.menuIds.split(','));
                
                setModalVisible(true);
                setCurrentRow(res.data);
              } else {
                message.warning(res.msg);
              }
            });
          }}
        >
          编辑
        </Button>,
        <div
          hidden={
            !access.hasPerms('system:tenant:edit') ||
            record.approvalStatus === '1' ||
            record.approvalStatus === '2'
          }
          key="Approval"
        >
          <Dropdown
            key="more"
            menu={{
              items: [
                {
                  label: '通过',
                  key: '1',
                  disabled: !access.hasPerms('system:tenant:edit'),
                },
                {
                  label: '拒绝',
                  key: '2',
                  disabled: !access.hasPerms('system:tenant:edit'),
                },
              ],
              onClick: async ({ key }) => {
                let body = { ...record };
                body.approvalStatus = key;
                const success = await handleUpdateApproval({ id: record.id, approvalStatus: key });
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              },
            }}
          >
            <a onClick={(e) => e.preventDefault()}>
              <Space>
                <DownOutlined />
                审核
              </Space>
            </a>

            {/* <Button type="link" size="small" key="more" ></Button> */}
          </Dropdown>
        </div>,
       

       

        <Button
          type="link"
          size="small"
          danger
          key="batchRemove"
          hidden={!access.hasPerms('system:tenant:remove')}
          onClick={async () => {
            Modal.confirm({
              title: '删除',
              content: '确定删除该项吗？',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                const success = await handleRemoveOne(record);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              },
            });
          }}
        >
          删除
        </Button>,
        <Button type='link' size='small' onClick={()=>{
          setShowMerchInComeBox(true)
          setMerchId(record.id)
        }}>商户进件</Button>,
        <Button type='link' size='small' disabled={record.userCardStatus==='2'} onClick={()=>{
          setShowBindCardConfirmBox(true)
          setbcTenantName(record.tenantName)
          setMerchId(record.id)
        }}>绑卡确认</Button>
      ],
    },
  ];

  return (
    <PageContainer>
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.System.Tenant>
          headerTitle={intl.formatMessage({
            id: 'pages.searchTable.title',
            defaultMessage: '信息',
          })}
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="id"
          key="tenantList"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="add"
              hidden={!access.hasPerms('system:tenant:add')}
              onClick={() => {
                setModalVisible(true);
                setCurrentRow(undefined);
              }}
            >
              <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
            </Button>,
            <Button
              type="primary"
              key="remove"              
              hidden={selectedRows?.length === 0 || !access.hasPerms('system:tenant:remove')}
              onClick={async () => {
                Modal.confirm({
                  title: '是否确认删除所选数据项?',
                  icon: <ExclamationCircleOutlined />,
                  content: '请谨慎操作',
                  async onOk() {
                    const success = await handleRemove(selectedRows);
                    if (success) {
                      setSelectedRows([]);
                      actionRef.current?.reloadAndRest?.();
                    }
                  },
                  onCancel() {},
                }); 
              }}
            >
              <DeleteOutlined />
              <FormattedMessage id="pages.searchTable.delete" defaultMessage="删除" />
            </Button>,
            <Button
              type="primary"
              key="export"
              hidden={!access.hasPerms('system:tenant:export')}
              onClick={async () => {
                handleExport();
              }}
            >
              <PlusOutlined />
              <FormattedMessage id="pages.searchTable.export" defaultMessage="导出" />
            </Button>,
          ]}
          request={(params) =>
            getTenantList({ ...params } as API.System.TenantListParams).then((res) => {
              const result = {
                data: res.data,
                total: res.total,
                success: true,
              };
              return result;
            })
          }
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />
      </div>
      {selectedRows?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />
              <a style={{ fontWeight: 600 }}>{selectedRows.length}</a>
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            key="remove"
            hidden={!access.hasPerms('system:tenant:del')}
            onClick={async () => {
              Modal.confirm({
                title: '删除',
                content: '确定删除该项吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                  const success = await handleRemove(selectedRows);
                  if (success) {
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  }
                },
              });
            }}
          >
            <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
          </Button>
        </FooterToolbar>
      )}
      <UpdateForm
        onSubmit={async (values) => {
          let success = false;

          if (currentRow && currentRow.createTime) {
            success = await handleUpdate({ ...values } as API.System.Tenant);
          } else {
            success = await handleAdd({ ...values } as API.System.Tenant);
          }
          if (success) {
            setModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        open={modalVisible}
        values={currentRow || {}}
        tenantpackages={tenantpackages || {}}

        
        statusOptions={statusOptions}
      />
     {
      showMerchInComeBox ? <MerchInCome  merchId={merchId} close={(isRefresh)=>{
        setShowMerchInComeBox(false)
        setMerchId(null)
        if(isRefresh&&actionRef.current){
          actionRef.current.reload();
        }
      }}></MerchInCome>:""
     }

      {
      showBindCardConfirmBox ? <BindCardComfirm merchId={merchId} tenantName={bcTenantName} close={(isRefresh)=>{
          setShowBindCardConfirmBox(false);
          if(isRefresh&&actionRef.current){
            actionRef.current.reload();
          }
      }}></BindCardComfirm>:''
     }
    </PageContainer>
  );
};

export default TenantTableList;
